<?php
namespace Lib\Doctrine;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
class InvokedRepository extends EntityRepository{
    /**
     * Deletes entities specified by single id-key or array of id-keys
     * @param mixed $ids
     * @return bool
     */
    public function delete($ids = null){
        $classMetadata = $this->getClassMetadata();
        return $this->deleteBy($classMetadata->getSingleIdentifierFieldName(), $ids);
    }

    /**
     * Deletes enities specified by column name and it single or multiple value
     * @param string $fieldName
     * @param mixed $fieldValues
     * @return bool
     */
    public function deleteBy($fieldName, $fieldValues){
        $classMetadata  = $this->getClassMetadata();
        $tableName      = $this->_entityName;
        $qb             = $this->_em->createQueryBuilder();

        // Property is not setted
        if(null === $fieldName){
            return false;
        }

        // Property is not existed
        if(!$classMetadata->hasField($fieldName)){
            return false;
        }

        // Creating query fo deleting
        $qb->delete()->from($tableName, 'i');
        if(is_array($fieldValues)){
            $whereCondition = $qb->expr()->in('i.'.$fieldName, $fieldValues);
        } else {
            $whereCondition = $qb->expr()->eq('i.'.$fieldName, $fieldValues);
        }
        $qb->where($whereCondition);
        return $qb->getQuery()->execute();
    }
}
